package org.xxpay.pay.channel.xypay;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.JsonUtil;
import org.xxpay.core.common.util.MD5Util;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.HashMap;
import java.util.Map;

@Service
public class XypayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(XypayPaymentService.class);

    @Override
    public String getChannelName() {
        return XypayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case XypayConfig.CHANNEL_NAME_ALIPAY_H5 :
                retObj = doPay(payOrder, "alipay_h5");
                break;
            default:
                retObj = ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     *
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder, String type) {
        XypayConfig xypayConfig = new XypayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();

        String host = xypayConfig.getReqUrl();
        String path = "/api/v1/data/order";
        String method = "POST";
        String token = xypayConfig.getMchId();
        String secret = xypayConfig.getKey();
        String orderid = payOrder.getPayOrderId(); //订单号
        String money = AmountUtil.convertCent2DollarShort(payOrder.getAmount()+""); //金额
        String attach = "线下收款"; // 备注
        String ip = "127.0.0.1"; // 客户端IP
        String callbackurl = super.getReturnUrl(getChannelName(), dbConfig); //回调
        String notifyurl = super.getNotifyUrl(getChannelName(), dbConfig); //异步回调
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("token",token);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("orderid", orderid);
        querys.put("type", type);
        querys.put("money", money);
        querys.put("attach", attach);
        querys.put("ip", ip);
        querys.put("callbackurl", callbackurl);
        querys.put("notifyurl", notifyurl);
        querys.put("sign", MD5Util.string2MD5("attach="+attach+"&callbackurl="+callbackurl+"&ip="+ip+"&money="+money+"&notifyurl="+notifyurl+"&orderid="+orderid+"&type="+type+"&key="+secret));
        try {
            //生成签名
            _log.info("{}请求数据:{}", getChannelName(), querys);
            HttpResponse response = XypayUtil.doPost(host, path, method, headers, querys, "");
            String result = EntityUtils.toString(response.getEntity());
            _log.info("{}返回数据:{}", getChannelName(), result);
            JSONObject jsonObject = JsonUtil.getJSONObjectFromJson(result);
            // {"status_code":200,"message":"success","data":{"pay_url":"http:\/\/pdd3.a16b6.cn\/index\/pay\/alipay_h5?order_sn=200229-598921872050789&href=https%3A%2F%2Fbaidu.com","started_at":"2020-02-29 22:19:56","valid_at":"2020-02-29 23:19:56"}}
            String code = jsonObject.getString("status_code");
            if("200".equals(code)) {    // 请求成功
                JSONObject data = jsonObject.getJSONObject("data");
                String payUrl = data.getString("pay_url");     // 支付URL
                int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), payUrl, type, updateCount);
                retObj.setJumpInfo("<script>location.href='" + payUrl + "';</script>", payUrl);
                return retObj;
            }else {
                String msg = jsonObject.getString("message");
                return ApiBuilder.bizError("调起通道失败[通道提示：" + msg +"]");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("调起通道异常");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "【" + getChannelName() + "支付订单查询】";
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询,payOrderId={}", logPrefix, payOrderId);
        return QueryRetMsg.waiting();
    }

}
